package com.xb.algorithm.web;

import com.alibaba.fastjson.JSONObject;
import com.xb.algorithm.annotation.AuthToken;
import com.xb.algorithm.dao.UserMapper;
import com.xb.algorithm.model.ResponseTemplate;
import com.xb.algorithm.entity.UserPO;
import com.xb.algorithm.service.TokenGeneratorService;
import com.xb.algorithm.utils.ConstantKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

/**
 * @author xb
 * @descripton: 欢迎页控制类
 * @date 2021/12/26
 */
@Slf4j
@RestController
public class WelcomeController {
    @Autowired
    private TokenGeneratorService tokenGenerator;

    @Autowired
    private UserMapper userMapper;

    /**
     * 欢迎页接口
     * @return
     */
    @GetMapping("/welcome")
    public String welcome() {
        return "welcome token authentication";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ResponseTemplate login(String username, String password) {

        log.info("username:"+username+"      password:"+password);

        UserPO user = userMapper.getUser(username,password);

        log.info("user:"+user);

        JSONObject result = new JSONObject();
        if (user != null) {

            Jedis jedis = new Jedis("127.0.0.1", 6379);
            String token = tokenGenerator.generate(username, password);
            jedis.set(username, token);
            //设置key生存时间，当key过期时，它会被自动删除，时间是秒
            jedis.expire(username, ConstantKit.TOKEN_EXPIRE_TIME);
            jedis.set(token, username);
            jedis.expire(token, ConstantKit.TOKEN_EXPIRE_TIME);
            Long currentTime = System.currentTimeMillis();
            jedis.set(token + username, currentTime.toString());

            //用完关闭
            jedis.close();

            result.put("status", "登录成功");
            result.put("token", token);
        } else {
            result.put("status", "登录失败");
        }

        return ResponseTemplate.builder()
                .code(200)
                .message("登录成功")
                .data(result)
                .build();

    }

    @RequestMapping(value = "test", method = RequestMethod.GET)
    @AuthToken
    public ResponseTemplate test() {

        log.info("已进入test路径");

        return ResponseTemplate.builder()
                .code(200)
                .message("Success")
                .data("test url")
                .build();
    }
}
